package com.itcast.controller;


import com.aliyuncs.utils.StringUtils;
import com.itcast.config.ValidateImageCodeUtils;
import com.itcast.service.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/index")
public class Indec {

    @Autowired
    private SendSms sendSms;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //响应图片
    @GetMapping("/getcode")
    public void getCode(HttpSession session, HttpServletResponse response) throws IOException {
        //生成验证码
        String code = ValidateImageCodeUtils.getSecurityCode();
        System.out.println(code);
        //存入session
        session.setAttribute("code",code);
        //Object code1 = session.getAttribute("code");
        //System.out.println("得到的code"+code1);
        //生成图片
        BufferedImage image = ValidateImageCodeUtils.createImage(code);
        //响应出去
        ServletOutputStream os = response.getOutputStream();
        ImageIO.write(image,"png",os);
    }


    @GetMapping("/ssm")
    @ResponseBody
    public String code(String phone){
        //调用发送方法
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){ //不为空
            return "验证码已存在";
        }

        //生成验证码并存储到redis
        code= UUID.randomUUID().toString().substring(0, 6);
        Map<String, Object> map = new HashMap<>();
        map.put("code",code);
        boolean send = sendSms.send(phone, "SMS_192825738", map);
        if(send){
            redisTemplate.opsForValue().set(phone,code, 5, TimeUnit.MINUTES);
            return "111";
        }else {
            return "验证码发送失败";
        }
    }





}
